package com.mjh.zhujianju.controller.base;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.HashMap;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.livew.framework.base.model.FileEO;
import com.livew.framework.base.service.FileService;
import com.livew.framework.exception.XTBusinessException;
import com.livew.framework.fastdfs.ConstantUtil;
import com.livew.framework.fastdfs.DfsHandler;
import com.livew.framework.pojo.AjaxResult;

@RestController
@RequestMapping("file")
public class FileController {

	@Resource
	private FileService fileService;
	
	//图片上传大小 2M
	private static Long photo_size = 2097152L;
	
	
	@RequestMapping(value = "/upload")
	public AjaxResult upload(@RequestParam(value = "file") MultipartFile file,
			HttpServletRequest request) throws Exception {
		if (photo_size < file.getSize()) {
			return AjaxResult.getResult(Boolean.FALSE, "请上传小于2M的图片");
		}
		FileEO f = fileService.insertDfs(file);
		return AjaxResult.getResult(Boolean.TRUE, f.getId() + "",f);
	}

	
	/**
	 * 展示图片
	 *
	 * @param fileId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value ="showImage/{id}" ,method = RequestMethod.GET)
	public void showImage(@PathVariable("id")Long id, HttpServletResponse response) throws XTBusinessException,Exception {
		FileEO file = fileService.getByPrimaryKey(id);
		if (file == null) {
			return ;
		}
		DfsHandler handler = DfsHandler.getInstance(ConstantUtil.TRACKER);
        byte[] bytes = handler.getBytes(file.getGroupname(),file.getRemotefilename());
        String fileName =file.getSrcname().toLowerCase();
        if (fileName.lastIndexOf(".jpg") == -1 && fileName.lastIndexOf(".png") == -1
                && fileName.lastIndexOf(".jpeg") == -1 && fileName.lastIndexOf(".gif") == -1
                && fileName.lastIndexOf(".bmp") == -1) {
            BufferedInputStream bis = null;
            ServletOutputStream fos = null;
            byte[] buf = new byte[1024];
            int size = 0;
            bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
            response.setContentType("multipart/form-data");
            String realfilename = "";
            try {
                //防止乱码
                realfilename = new String(file.getSrcname().getBytes("UTF-8"), "ISO8859-1");
            } catch (Exception e) {
                e.printStackTrace();
            }
            //设置文件名
            response.setHeader("Content-Disposition", "attachment;fileName=" + realfilename);
            fos = response.getOutputStream();
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();
        }else if (fileName.lastIndexOf(".jpg") >0 ||fileName.lastIndexOf(".png") >0 ||
                fileName.lastIndexOf(".jpeg") >0 || fileName.lastIndexOf(".gif") >0 ||
                fileName.lastIndexOf(".bmp") >0 ) {
            BufferedInputStream bis = null;
            ServletOutputStream fos = null;
            byte[] buf = new byte[1024];
            int size = 0;
            bis = new BufferedInputStream(new ByteArrayInputStream(bytes));
           String type = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
           // "image/png"
            response.setContentType("image/"+type);
//            response.setContentType("image/jpg");
            String realfilename = "";
            try {
                //防止乱码
                realfilename = new String(file.getSrcname().getBytes("UTF-8"), "ISO8859-1");
            } catch (Exception e) {
                e.printStackTrace();
            }
            //设置文件名
//            response.setHeader("Content-Disposition", "attachment;fileName=" + realfilename);
            fos = response.getOutputStream();
            while ((size = bis.read(buf)) != -1)
                fos.write(buf, 0, size);
            fos.close();
            bis.close();
        }
        
	}
	
	
	/**
	 * 展示图片
	 *
	 * @param fileId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value ="showQCode" ,method = RequestMethod.GET)
	public void showImage(String content, HttpServletResponse response) throws XTBusinessException,Exception {
		int width=300;
        int height=300;
        String format="png";
        String contents=content;
        HashMap map=new HashMap();
        map.put(EncodeHintType.CHARACTER_SET, "utf-8");
        map.put(EncodeHintType.ERROR_CORRECTION,ErrorCorrectionLevel.M);
        map.put(EncodeHintType.MARGIN, 0);
        try {
            BitMatrix bm = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height);
            File file=new File("C://img.png");
            Path path =  file.toPath();
            MatrixToImageWriter.writeToPath(bm, format, path);
            file.delete();
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
